import React, {useReducer} from 'react'
// useReducer 这个函数的作用是在函数组件中使用redux相关功能
// 准备工作：初始化state、准备reducer

const initState = {
  age: 18
}
// 准备纯函数，用来修改数据
const reducer = (state=initState, action)=>{
  switch (action.type) {
    case 'old':
      return {
        ...state,
        age: state.age + 1
      }
    case 'young':
      return {
        ...state,
        age: state.age - 1
      }  
    default:
      return state
  }
}

export default function ReducerFn() {
  // useReducer这个函数有两个参数：reducer，初始化的state
  // 返回值也是两个：state以及修改数据的dispatch
  const [state, dispatch] = useReducer(reducer, initState);
  const old = ()=> {
    dispatch({type: 'old'})
  }
  const young = ()=> {
    dispatch({type: 'young'})
  }
  return (
    <div>
      <p>useReducer</p>
      <p>当前年龄：{state.age}</p>
      <button onClick={()=>old()}>长大一岁</button>
      <button onClick={()=>young()}>年轻一岁</button>
    </div>
  )
}
